package com.example.mytips.utils;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.http.util.TextUtils;

import java.io.File;
import java.io.IOException;

public class ShowInFinder {

    public static void showInFiner(String folderPath, AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) {
            return;
        }

        if (TextUtils.isEmpty(folderPath)) {
            Messages.showInfoMessage(project, "文件目录地址为空", "提示");
            return;
        }

        File folder = new File(folderPath);
        if (folder.exists()) {
            VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(folder);
            if (virtualFile != null) {

                String os = System.getProperty("os.name").toLowerCase();
                if (os.contains("win")) {
                    System.out.println("Windows");
                    // 使用 Runtime 执行命令，在资源管理器中打开文件夹并选中文件
                    try {
                        // 构造命令行
                        String[] command = new String[]{"explorer.exe", "/select,", folderPath};
                        // 执行命令
                        Runtime.getRuntime().exec(command);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                } else if (os.contains("mac")) {
                    System.out.println("macOS");
                    // 使用 Runtime 执行命令，在 Finder 中打开文件夹并选中文件
                    try {
                        Runtime.getRuntime().exec(new String[]{"open", "-R", folderPath});
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                } else {
                    System.out.println("Unknown");
                }

            }
        } else {
            //文件不存在
            Messages.showInfoMessage(project, "文件不存在", "提示");
        }
    }
}
